昨天稍微講解了Dependency Injection,今天要來介紹dagger了。
經常使用的annotation
public class Fruit {
private String name;
private String price;
public Fruit(String name, String price){
this.name=name;
this.price=price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
提供Fruit
需要的依賴實例。@Named
@Named("Name")將他回傳的String命名為Name, 當使用provideFruit(@Named("name")String name,@Named("price")String price)需要其中的
@Named("name")String name`時,就能找到對應的String。
@Module
public class Fruit1Module {
private String name;
private String price;
public Fruit1Module(String name,String price){
this.name=name;
this.price=price;
}
//表示回傳的string會傳入Fruit.class
@Provides
Fruit provideFruit(@Named("name")String name,@Named("price")String price){
return new Fruit(name,price);
}
@Provides
@Named("name")
String provideFruit1Name(){
return name;
}
@Provides
@Named("price")
String provideFruit1Price(){
return price;
}
}
@Component(modules = Fruit1Module.class)標記要引用的Module
@Component(modules = Fruit1Module.class)
public interface Fruit1Component {
void inject(Test1Activity test1Activity);//代表Fruit1Component注入到Test1Activity,那麼在Test1Activity可使用@inject註解變量生成實例。
}
使用@Inject 注入Fruit class讓Fruit被賦值。
按下build->rebuild project(快速鍵ctrl+f9)
進行compile,編譯完dagger會產生DaggerFruit1Component
。使用如下:
public class Test1Activity extends AppCompatActivity {
private Fruit1Component fruit1Component;
@Inject
Fruit fruit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test1);
setting();
}
private void setting() {
fruit1Component= DaggerFruit1Component.builder() //將實體建立
.fruit1Module(new Fruit1Module("apple","20"))
.build();
fruit1Component.inject(this); //將建立完的實體inject到Test1Activity
String text = fruit.getName();
Log.d("fruit",text);
}
}
log結果: